package com.security.brows.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.icu.text.SimpleDateFormat
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.room.RoomOpenHelper
import coil.compose.AsyncImage
import com.hub.videobrowsdownload.R
import com.security.brows.base.SecurityBaseActivity
import com.security.brows.room.BrowsRoomHelper
import com.security.brows.room.BrowsWebHistoryBean
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.ref.WeakReference
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale

class SecurityBrowsHistoryActivity : SecurityBaseActivity() {
    companion object {
        var cacheHistoryActivity:WeakReference<Activity>? = null
        fun start(context: Context) {
            try {
                if (cacheHistoryActivity != null && cacheHistoryActivity?.get()?.isFinishing != true) {
                    cacheHistoryActivity?.get()?.finish()
                    cacheHistoryActivity = null
                }
            } catch (e: Exception) {

            }
            context.startActivity(Intent(context, SecurityBrowsHistoryActivity::class.java))
        }
    }

    override fun preContent() {
        super.preContent()
        cacheHistoryActivity = WeakReference(this)
    }
    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    override fun ComposeContent(
        isDarkTheme: Boolean,
        colorsScheme: SecurityBrowsColorsScheme,
        drawableScheme: SecurityBrowsDrawable
    ) {

        val onBackPressedDispatcherOwner = LocalOnBackPressedDispatcherOwner.current
        val isEditMode = remember {
            mutableStateOf(false)
        }
        val context = LocalContext.current
        val historyList =
            BrowsRoomHelper.getDao(context = context).getWebHistoryFlow().collectAsState(
                initial = emptyList()
            )

        val editList = remember {
            mutableStateMapOf<Long, BrowsWebHistoryBean>()
        }
        val scope = rememberCoroutineScope()
        BackHandler(isEditMode.value) {
            editList.clear()
            isEditMode.value = false
        }

        Column(
            Modifier
                .fillMaxSize()
                .background(colorsScheme.browsBg)
        ) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(60.dp)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(50.dp)
                        .clickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple()) {
                            onBackPressedDispatcherOwner?.onBackPressedDispatcher?.onBackPressed()
                        }
                ) {
                    Image(
                        painter = painterResource(id = drawableScheme.back),
                        contentDescription = null,
                        modifier = Modifier
                            .align(
                                Alignment.Center
                            )
                            .size(20.dp)
                    )
                }
                Text(
                    text = "History",
                    color = colorsScheme.homeTitle,
                    fontSize = 20.sp,
                    modifier = Modifier
                        .align(Alignment.CenterVertically)
                )
            }
            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(12.dp)
                    .background(colorsScheme.homeTitleSpace)
            )

            if (historyList.value.isEmpty()) {
                Column(
                    Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Image(
                        painter = painterResource(id = drawableScheme.no_pending),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(horizontal = 80.dp)
                            .fillMaxWidth(),
                        contentScale = ContentScale.FillWidth
                    )

                    Spacer(modifier = Modifier.height(13.dp))

                    Image(
                        painter = painterResource(id = drawableScheme.how_to_download),
                        contentDescription = null,
                        modifier = Modifier
                            .padding(top = 64.dp, start = 60.dp, end = 60.dp)
                            .fillMaxWidth()
                            .clickable(interactionSource = remember {
                                MutableInteractionSource()
                            }, indication = rememberRipple()) {
                                SecurityBrowsGuideActivity.start(context)
                            },
                        contentScale = ContentScale.FillWidth
                    )

                }
            } else {
                LazyColumn(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .padding(horizontal = 12.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp)
                ) {
                    item {
                        Spacer(modifier = Modifier.height(14.dp))
                    }

                    items(historyList.value, key = {it.time}) {
                        Row(
                            Modifier.animateItemPlacement()
                                .fillMaxWidth()
                                .height(76.dp)
                                .background(colorsScheme.historyItemBg, RoundedCornerShape(10.dp))
                                .combinedClickable(interactionSource = remember {
                                    MutableInteractionSource()
                                }, indication = rememberRipple(), onLongClick = {
                                    if (!editList.containsKey(it.time)) {
                                        editList.put(it.time, it)
                                    }
                                    isEditMode.value = true
                                }) {
                                    if (isEditMode.value) {
                                        if (editList.contains(it.time)) {
                                            editList.remove(it.time)
                                            if (editList.isEmpty()) {
                                                isEditMode.value = false
                                            }
                                        } else {
                                            editList.put(it.time, it)
                                        }
                                    } else {
                                        SecurityBrowsTabWebActivity.start(context, it.webUrl)
                                    }
                                }, verticalAlignment = Alignment.CenterVertically
                        ) {
                            Spacer(modifier = Modifier.width(14.dp))
                            AsyncImage(
                                model = if (it.icon.isNullOrEmpty()) it.iconUrl else it.icon,
                                contentDescription = null,
                                modifier = Modifier
                                    .clip(CircleShape)
                                    .size(38.dp),
                                contentScale = ContentScale.Crop
                            )
                            Spacer(modifier = Modifier.width(11.dp))
                            Column(Modifier.weight(1f)) {
                                val title = it.title
                                val showTitle = if (title.isNullOrEmpty()) it.webUrl else it.title
                                Text(
                                    text = showTitle ?: "",
                                    fontSize = 14.sp,
                                    color = colorsScheme.historyItemTitle,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                                if (!title.isNullOrEmpty()) {
                                    Spacer(modifier = Modifier.height(3.dp))
                                    Text(
                                        text = it.webUrl ?: "",
                                        fontSize = 12.sp,
                                        color = colorsScheme.historyItemDesc,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis
                                    )
                                }
                                Spacer(modifier = Modifier.height(3.dp))
                                val customFormatter = SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.getDefault())
                                Text(
                                    text =  customFormatter.format(Date(it.time)),
                                    fontSize = 8.sp,
                                    color = colorsScheme.historyItemDesc,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                            if (isEditMode.value && editList.contains(it.time)) {
                                Spacer(modifier = Modifier.width(11.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.brows_select_),
                                    contentDescription = null,
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                            Spacer(modifier = Modifier.width(12.dp))
                        }
                    }

                    item {
                        Spacer(modifier = Modifier.height(14.dp))
                    }
                }
                if (isEditMode.value) {
                    Row(
                        modifier = Modifier
                            .height(60.dp)
                            .background(colorsScheme.homeTabBg)
                    ) {
                        if (editList.size == historyList.value.size) {
                            TableItem(
                                iconN = drawableScheme.history_select_all_on,
                                name = "Select all",
                                color = colorsScheme.homeTableSelect
                            ) {
                                editList.clear()
                            }
                        } else {
                            TableItem(
                                iconN = drawableScheme.history_select_all,
                                name = "Select all",
                                color = colorsScheme.homeTable
                            ) {
                                editList.clear()
                                scope.launch {
                                    withContext(Dispatchers.IO){
                                        try {
                                            for (i in historyList.value) {
                                                editList.put(i.time, i)
                                            }
                                        } catch (e: Exception) {
                                        }
                                    }
                                }
                            }
                        }
                        TableItem(
                            iconN = drawableScheme.history_delete,
                            name = "Delete",
                            color = colorsScheme.homeTableSelect
                        ) {
                            scope.launch {
                                withContext(Dispatchers.IO) {
                                    for (i in editList.values) {
                                        i.delete(context)
                                    }
                                }
                                editList.clear()
                                isEditMode.value = false
                            }
                        }

                    }
                }
            }
        }
    }


    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    private fun RowScope.TableItem(
        iconN: Int,
        name: String,
        color: Color,
        clickAble: () -> Unit,
    ) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .weight(1f)
        ) {

            Column(
                Modifier
                    .fillMaxSize()
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple(), onClick = clickAble),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {

                Image(
                    painter = painterResource(id = iconN),
                    contentDescription = null,
                    modifier = Modifier.size(28.dp)
                )
                Spacer(modifier = Modifier.height(2.dp))
                Text(
                    text = name,
                    fontSize = 12.sp,
                    color = color
                )
            }


        }
    }
}